package com.lianqi.emcpframework.extend.script;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @program emcp-framework
 * @ClassName ListenerSupportEngine
 * @description: 支持监听器的脚本引擎定义
 * @author: sky
 * @create: 2018/12/04 19:49
 */
public abstract class ListenerSupportEngine implements DynamicScriptEngine {

    protected List<ScriptListener> listeners = new LinkedList<>();
    private Map<String,Object> globalVariables;

    protected void doListenerBefore(ScriptContext context){
        listeners.forEach(listener -> listener.before(context));
    }
    protected void doListenerAfter(ScriptContext context,ExecuteResult result){
        listeners.forEach(listener -> listener.after(context,result));
    }

    @Override
    public void addListener(ScriptListener listener) {
        listeners.add(listener);
    }

    protected Map<String,Object> getGlobalVariables(){
        if (globalVariables == null){
            return new HashMap<>();
        }
        return new HashMap<>(globalVariables);
    }

    @Override
    public void addGlobalVariable(Map<String, Object> vars) {
        if (globalVariables == null){
            globalVariables = new HashMap<>();
        }
        globalVariables.putAll(vars);
    }
}
